package service

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"
	"user-srv/basic/inits"
	__ "user-srv/basic/proto"
	"user-srv/handler/model"
	"user-srv/pkg"
)

type Server struct {
	__.UnimplementedStreamGreeterServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000

	get := inits.Rdb.Get(inits.Ctx, "Sendsms")
	if get.Val() >= "3" {
		return nil, fmt.Errorf("一分钟只能发送三次")
	}
	var Sms pkg.AliyunSms

	err := Sms.Send(in.Phone, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	inits.Rdb.Set(inits.Ctx, "SendSms", code, time.Hour*2)
	inits.Rdb.Incr(inits.Ctx, "Sendsms")
	inits.Rdb.Expire(inits.Ctx, "Sendsms", time.Minute*1)
	return &__.SendSmsResp{}, nil
}

// 注册用户
func (s *Server) UserAdd(_ context.Context, in *__.UserAddReq) (*__.UserAddResp, error) {
	user := model.User{
		Username: in.Username,
		Phone:    in.Phone,
		Password: pkg.Md5(in.Password),
	}
	get := inits.Rdb.Get(inits.Ctx, "SendSms")
	if get.Val() != in.SendSms {
		return nil, fmt.Errorf("短息错误")
	}
	inits.DB.Debug().Where("phone=?", in.Phone).Find(&user)
	if user.ID != 0 {
		return nil, fmt.Errorf("手机号已注册")
	}

	inits.DB.Debug().Create(&user)
	return &__.UserAddResp{
		Id: int64(user.ID),
	}, nil
}

// 功能录入
func (s *Server) VideoAdd(_ context.Context, in *__.VideoAddReq) (*__.VideoAddResp, error) {
	video := model.Video{
		Title:   in.Title,
		Desc:    in.Desc,
		Address: in.Address,
	}
	inits.DB.Debug().Where("desc=?", in.Desc)
	if video.Title == "" {
		return nil, fmt.Errorf("视频内容不能为空")
	}
	inits.DB.Debug().Create(&video)
	return &__.VideoAddResp{
		Id: int64(video.ID),
	}, nil
}

// 搜索
func (s *Server) VideoFind(_ context.Context, in *__.VideoFindReq) (*__.VideoFindResp, error) {
	var videos model.Video

	inits.DB.Debug().Where("id=?", videos.ID).Find(&videos)
	return &__.VideoFindResp{
		Title:   videos.Title,
		Desc:    videos.Desc,
		Address: videos.Address,
	}, nil
}

// 多维度添加
func (s *Server) LabelAdd(_ context.Context, in *__.LabelAddReq) (*__.LabelAddResp, error) {
	label := model.Label{
		Address: in.Address,
		Subject: in.Subject,
		Att:     in.Att,
	}

	inits.DB.Debug().Create(&label)
	return &__.LabelAddResp{
		Id: int64(label.ID),
	}, nil
}

// 统计分析
func (s *Server) TableList(_ context.Context, in *__.TableListReq) (*__.TableListResp, error) {

	var tablelist []model.Table
	inits.DB.Debug().Find(&tablelist)
	var lists []*__.ReqTable
	for _, table := range tablelist {
		list := &__.ReqTable{
			Watch: table.Watch,
			Like:  int64(table.Like),
			Score: table.Score,
		}
		lists = append(lists, list)
	}
	return &__.TableListResp{
		List: lists,
	}, nil
}

// 订阅添加
func (s *Server) DurationAdd(_ context.Context, in *__.DurationAddReq) (*__.DurationAddResp, error) {
	duration := model.Watch{
		Name:     in.Name,
		Duration: in.Duration,
		PutDate:  in.Putdate,
	}
	inits.DB.Debug().Where("name=?", in.Name).Find(&duration)
	if duration.ID == 0 {
		return nil, fmt.Errorf("名称为空 不能订阅")
	}
	inits.DB.Debug().Create(&duration)
	return &__.DurationAddResp{
		Id: int64(duration.ID),
	}, nil
}

// 收藏
func (s *Server) Collect(_ context.Context, in *__.CollectReq) (*__.CollectResp, error) {
	collect := model.Watch{
		Collect: int(in.Collect),
	}

	inits.DB.Debug().Where("name=?", collect.Name).Find(&collect)
	if collect.ID == 0 {
		return nil, fmt.Errorf("视频不存在 无法收藏")
	}
	inits.DB.Debug().Create(&collect)
	return &__.CollectResp{
		Id: int64(collect.ID),
	}, nil
}

// 排序
func (s *Server) VideoList(_ context.Context, in *__.VideoListReq) (*__.VideoListResp, error) {
	var videolist []model.Video
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	inits.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Find(&videolist)
	inits.Rdb.Set(inits.Ctx, "Page", page, time.Hour*2)
	var lists []*__.ReqVideoList
	for _, video := range videolist {
		list := &__.ReqVideoList{
			Title:   video.Title,
			Desc:    video.Desc,
			Address: video.Address,
		}
		lists = append(lists, list)
	}

	return &__.VideoListResp{
		List: lists,
	}, nil
}

// 筛选
func (s *Server) Table(_ context.Context, in *__.TableReq) (*__.TableResp, error) {
	var table model.Table
	//inits.DB.Debug().Where("id=?", table.ID).Find(&table)
	//if table.Like == 0 {
	//	return nil, fmt.Errorf("数据不存在,无法查询")
	//}

	inits.DB.Debug().Create(&model.Table{
		Watch: in.Watch,
		Like:  int(in.Like),
		Score: in.Score,
	})
	return &__.TableResp{
		Id: int64(table.ID),
	}, nil
}

// 观看历史
func (s *Server) WatchList(_ context.Context, in *__.WatchListReq) (*__.WatchListResp, error) {
	var Scorelist []model.Watch
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	inits.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Find(&Scorelist)
	inits.DB.Debug().Find(&Scorelist)
	var lists []*__.ReqWatch
	for _, video := range Scorelist {
		list := &__.ReqWatch{
			Name:     video.Name,
			Duration: video.Duration,
			Putdate:  video.PutDate,
			Collect:  int64(video.Collect),
		}
		lists = append(lists, list)
	}
	return &__.WatchListResp{
		List: lists,
	}, nil
}

// 统计
func (s *Server) Watch(_ context.Context, in *__.WatchReq) (*__.WatchResp, error) {
	watch := model.Video{
		Title:   in.Title,
		Desc:    in.Desc,
		Address: in.Address,
	}
	inits.DB.Debug().Create(&watch)
	return &__.WatchResp{
		Id: int64(watch.ID),
	}, nil
}

// 会员权益
func (s *Server) Member(_ context.Context, in *__.MemberReq) (*__.MemberResp, error) {
	member := model.Member{
		Type: in.Type,
		Vip:  in.Vip,
	}

	if member.Vip != "vip" {
		return nil, fmt.Errorf("不是vip用户只能是看三分钟")
	}
	inits.DB.Debug().Create(&member)
	return &__.MemberResp{
		Id: int64(member.ID),
	}, nil
}

// 积分排名
func (s *Server) Score(_ context.Context, in *__.ScoreReq) (*__.ScoreResp, error) {
	var Score []model.Score
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	inits.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Find(&Score)
	var lists []*__.ReqScore
	for _, video := range Score {
		list := &__.ReqScore{
			Videoid: int64(video.VideoId),
			Score:   video.Score,
		}
		lists = append(lists, list)
	}
	return &__.ScoreResp{
		List: lists,
	}, nil
}
